<template>
  <p @click="activeDraw">发布公告</p>
  <div>
    <el-dialog class="lssueDialog" v-model="showDialog" style="width: 500px;height: 500px;" draggable
      @close="dialogClose">
      <template #header="{ titleId, titleClass }">
        <div class="my-header">
          <h4 :id="titleId" :class="titleClass" style="margin-left: 25px;margin-top: 0px;">发布公告</h4>
        </div>
      </template>
      <div style="position: relative;top: -20px;">
        <el-table :data="tableData" stripe border style="height: 300px;border: 1px solid black;">
          <el-table-column prop="name" label="物业" :header-align="'center'" :align="'center'"></el-table-column>
          <el-table-column prop="tel" label="电话" :header-align="'center'" :align="'center'"></el-table-column>
        </el-table>
      </div>
      <div style="position:relative;all:initial;top: 5px;">
        <span style="position: relative;top: -40px;">公告信息:</span>
        <textarea rows="4" cols="30" v-model="Content" placeholder="请输入要上传的公告信息"
          style="width: 330px;position: relative;left:10px;"></textarea>
      </div>
      <div id="btn" style="position: relative;top: -10px;">
        <el-button type="primary" style="position: relative;right: -170px;" @click="updateContent">确定</el-button>、
        <el-button style="position: relative;right: -160px;" @click="cancelLssue">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { createDraw } from '../../../../../utils/createDraw';
import { Query } from '../../../../../utils/Query';
import * as turf from '@turf/turf';
import { usePiniaStore } from '../../../../../stores/pinia'
import { storeToRefs } from "pinia";
const piniaStore = usePiniaStore()
const { textContent } = storeToRefs(piniaStore);
const { lssueTime } = storeToRefs(piniaStore)
//控制弹窗的显隐
const showDialog = ref(false);
let docLayer = new Zondy.Map.Doc("", "guanggu", {})
let $map = null
//生成画笔图层和数据源并添加到图层中
let drawSource = new ol.source.Vector({})
let drawLayer = new ol.layer.Vector({
  source: drawSource
})
//生成缓冲区图层和数据源并添加到图层中
let bufferSource = new ol.source.Vector({})
let bufferLayer = new ol.layer.Vector({
  source: bufferSource,
})
function createGradientStyle(){
  var colorStart = [255,0,0]
  var colorEnd = [255,255,0];
  var ratio = 0.3
  var colorIntermediate = colorStart.map(function (value, index) {
    return Math.round(value + ratio * (colorEnd[index] - value));
  })
  var style = new ol.style.Style({
    fill: new ol.style.Fill({
      color: 'rgba(' + colorIntermediate.join(',') + ', 0.6)' // 设置透明度为0.6的渐变颜色
    }),
    stroke: new ol.style.Stroke({
      color: 'rgba(255, 0, 0, 0.8)', // 设置边框颜色为红色，透明度为0.8
      width: 2 // 设置边框宽度
    })
  });
  return [style]
}
bufferLayer.setStyle(createGradientStyle);
onMounted(() => {
  // console.log("onMounted挂钩被执行");
  $map = inject("$map")
  // console.log($map)

})
let tableData = ref([])
const processResidentData = (affectResident) => {
  affectResident.forEach((item) => {
    tableData.value.push({
      name: item.values_.values_.name,
      tel: item.values_.values_.tel
    });
  });
}
/*	定义点击按钮的函数，启动画笔  */
function activeDraw() {
  $map.addLayer(drawLayer)
  $map.addLayer(bufferLayer)
  //创建画笔，以drawSource作为承载的数据源
  let draw = createDraw({
    type: "LineString",
    source: drawSource
  });
  $map.addInteraction(draw);
  draw.on("drawend", (evt) => {
    $map.removeInteraction(draw);//移除画笔
    //1、获取画的线的所有坐标点
    let drawLine = evt.feature;
    // console.log(drawLine);
    let coords = drawLine.getGeometry().getCoordinates()
    // console.log(coords);

    //缓冲区分析
    //2、生成turf的线对象
    let turfLine = turf.lineString(coords);
    // console.log(turfLine);
    //3、执行缓冲区分析，turf必须使用wgs84经纬度坐标系
    let bufferedTurfLine = turf.buffer(turfLine, 0.15, {
      //半径
      units: "kilometers",//单位
    });
    //4、将生成的缓冲区转换为Openlayers的面要素，并添加到响应的图层中进行展示
    let bufferFeature = new ol.format.GeoJSON().readFeatures(
      bufferedTurfLine
    );
    bufferSource.addFeatures(bufferFeature)
    Query.queryByLayer({
      service: { name: "guanggu", layerId: 0 },
      success: (data) => {
        let format = new Zondy.Format.PolygonJSON();

        let residentFeatures = format.read(data)
        let affectResident = []

        residentFeatures.forEach((residentFeature) => {
          let residentCoords = residentFeature.getGeometry().getCoordinates();
          let turfResiFeature = turf.polygon(residentCoords)

          let intersection = turf.intersect(
            turfResiFeature,
            bufferedTurfLine
          );
          if (intersection) {
            // console.log(residentFeatures, "相交");
            affectResident.push(residentFeature)
          }
        });
        // console.log(affectResident, "全部相交的居民区")
        processResidentData(affectResident)
      }
    })
    setTimeout(() => {
      showDialog.value = !showDialog.value;
    }, 1000)
  })
}
import { ElMessage } from 'element-plus'
// 获取文本框输入的值
let Content = ref('')
function updateContent() {
  // console.log(Content.value, 1111)
  if (Content.value == "") {
    ElMessage.error('提交内容为空，请重新输入')
  } else if (!textContent.value.includes(Content.value)) {
    textContent.value.push(Content.value)
    const nowTime = getCurrentTime()
    lssueTime.value.push(nowTime)
    ElMessage({
      message: '公告发布成功',
      type: 'success',
    })
    showDialog.value = !showDialog.value;
  }
  $map.removeLayer(bufferLayer)
  $map.removeLayer(drawLayer)
  bufferSource.clear()
  drawSource.clear()
  Content.value = ''
}
const getCurrentTime = () => {
  const currentTime = new Date()
  const year = currentTime.getFullYear();
  const month = currentTime.getMonth() + 1;
  const day = currentTime.getDate();
  const hours = currentTime.getHours(); // 获取小时
  const minutes = currentTime.getMinutes(); // 获取分钟
  const seconds = currentTime.getSeconds(); // 获取秒数 
  const times = `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`

  return times
}
function dialogClose() {
  $map.removeLayer(bufferLayer)
  $map.removeLayer(drawLayer)
  bufferSource.clear()
  drawSource.clear()
  Content.value = ''
}
function cancelLssue(){
  $map.removeLayer(bufferLayer)
  $map.removeLayer(drawLayer)
  bufferSource.clear()
  drawSource.clear()
  Content.value = ''
  showDialog.value = !showDialog.value;
}
</script>

<style lang="scss">
#btn {
  position: relative;
  left: 100px;
  right: 30px;
}

#textinput {
  position: relative;
  margin-top: 10px !important;
}
</style>